package front

import (
	"errors"
	"fmt"
	database "hft/Database"
	"hft/Database/admin"
	"hft/Http/Models/request"
	services "hft/Http/Services"
	utils "hft/Http/Utils"
	"hft/e"
	"hft/global"
	"hft/tools"
	"time"

	"github.com/tidwall/gjson"
	"gorm.io/gorm"
)

type Clue struct{}

func (*Clue) LeaveClue(data *request.Clue, city int) (err error) {
	var user *admin.User
	var region *admin.Region
	if err = global.OC_DB.First(&region, data.RegionId).Error; err != nil {
		return errors.New(e.RegionNotFound)
	}
	if region.ManageId == 0 {
		return errors.New(e.NoManagerHere)
	}
	var managerAccount *admin.Account
	if err := global.OC_DB.First(&managerAccount, region.ManageId).Error; err != nil {
		return errors.New(e.AccountNotExist)
	}
	var ca interface{}
	if data.Type == 0 {
		var activity *admin.CommonActivity
		if err = global.OC_DB.First(&activity, data.ActivityId).Error; err != nil {
			return errors.New(e.ActivityNotFound)
		}
		ca = (activity)
	} else if data.Type == 1 {
		var activity *admin.Activity
		if err = global.OC_DB.First(&activity, data.ActivityId).Error; err != nil {
			return errors.New(e.ActivityNotFound)
		}
		ca = activity
	} else {
		return errors.New(e.ActivityInValid)
	}
	var pageName string
	var louPan *admin.LouPan
	res := global.OC_DB.First(&louPan, data.LouPanId)
	if res.RowsAffected == 0 {
		pageName = ""
	} else {
		pageName = louPan.Name
	}
	var id = gjson.Get(tools.JsonParse(ca), "id").Int()
	var title = gjson.Get(tools.JsonParse(ca), "title").String()
	var belongName string
	belongName = utils.RegionBelong(fmt.Sprintf("%v%v,", region.Link, region.ID), global.OC_DB)
	res = global.OC_DB.Where("phone = ? AND city = ?", data.Phone, city).Preload("ClueList", func(db *gorm.DB) *gorm.DB {
		return db.Order("create_time desc")
	}).First(&user)
	if res.RowsAffected == 0 {
		var newUser = &admin.User{
			Phone:           data.Phone,
			RegionLink:      region.Link,
			City:            uint(city),
			Level:           "F",
			Valid:           2,
			UseProductTimes: 1,
			BrokerNum:       0,
			AccountLink:     fmt.Sprintf("%v%v,", managerAccount.AccountLink, managerAccount.ID),
		}
		var clue = &admin.Clue{
			OriginName:   data.OriginName,
			Phone:        data.Phone,
			ActivityName: title,
			ActivityId:   int(id),
			PageName:     pageName,
			LouPanId:     data.LouPanId,
			IP:           data.IP,
			Region:       data.RegionId,
			BelongName:   belongName,
			ComeLink:     data.ComeLink,
			Cont:         data.Cont,
		}
		err = services.UserService.CreateUser(newUser, clue)
		if err != nil {
			return err
		}
		err = services.BaseService.SendCode(data.Phone, "USER_")
		if err != nil {
			return errors.New("发送验证码失败")
		}
	} else {
		var userTimes int
		if utils.IsTimeDifferenceGreaterThan24Hours(time.Now(), user.CreateTime) {
			userTimes = user.UseProductTimes + 1
		}
		var newUser = &admin.User{
			Base:            database.Base{ID: user.ID},
			RegionLink:      region.Link,
			City:            uint(city),
			UseProductTimes: userTimes,
			AccountLink:     fmt.Sprintf("%v%v,", managerAccount.AccountLink, managerAccount.ID),
		}
		var clue = &admin.Clue{
			UserId:       int(user.ID),
			OriginName:   data.OriginName,
			ActivityName: title,
			ActivityId:   int(id),
			PageName:     pageName,
			LouPanId:     data.LouPanId,
			IP:           data.IP,
			IpRegion:     data.IpRegion,
			Region:       data.RegionId,
			BelongName:   belongName,
			ComeLink:     data.ComeLink,
			Cont:         data.Cont,
		}
		services.UserService.UpdateUser(newUser, clue)

	}

	return nil
}

func (*Clue) ValidCode(data request.ValidCode, sid int) (err error) {

	err = tools.AliyunSmsTool.VerifyValid("USER_", data.Phone, data.Code)

	if err != nil {
		return err
	}

	res := global.OC_DB.Model(&admin.User{}).Where("phone = ? AND city = ? AND valid = ?", data.Phone, sid, 2).Update("valid", 1)

	if res.RowsAffected == 0 {
		return errors.New("该用户已验证")
	}

	if res.Error != nil {
		return errors.New("未知错误500")
	}

	return nil

}

var ClueFrontService = new(Clue)
